package domain;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

public class MulticastStatusVersionThread extends Thread{

	private String serverIp;
	private int port;
	private String multicastAddress;
	private long WAITING_TIME = 1000;  // 1 seconden
	private byte[] buf;
	private long currentServerStatusId;
	
	private DatagramSocket socket;
	
	public MulticastStatusVersionThread(int port, String multicastAddress) throws SocketException {
		super();
		this.port = port;
		this.multicastAddress = multicastAddress;
		socket = new DatagramSocket(port);
	}
    
	public void run() {
		while(true){
			try {
				currentServerStatusId = Server.getServerStatusVersionId();
				
				buf = ByteBuffer.allocate(8).putLong(currentServerStatusId).array(); //long should be 8 bytes in Java
				System.out.println("send id: length = "+ buf.length + ", id = " + currentServerStatusId);
				InetAddress group = InetAddress.getByName(multicastAddress);
				DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
				socket.send(packet);
				sleep(WAITING_TIME);
				
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	

}
